package com.example.spring_project.service.impl;

import com.example.spring_project.entity.LoginBody;
import com.example.spring_project.service.CaptchaService;
import com.example.spring_project.utils.IdUtils;
import com.example.spring_project.utils.ImageUtil;
import com.example.spring_project.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Base64;
import java.util.Objects;
import java.util.concurrent.TimeUnit;


@Service
public class CaptchaServiceImpl implements CaptchaService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;  // RedisTemplate

    private static final long EXPIRE_SECONDS = 120; // 验证码过期时间（秒）



    @Override
    public Result<Object> generateCaptcha() {
        ImageUtil imageUtil = ImageUtil.getInstance(); // 获取 ImageUtil 实例
        ByteArrayInputStream image = imageUtil.getImage(); // 获取验证码图片

        // 保存验证码信息
        String uuid = IdUtils.simpleUUID();
        redisTemplate.opsForValue().set(uuid, resolveCaptcha(imageUtil.getStr()), EXPIRE_SECONDS, TimeUnit.SECONDS);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] bytes = new byte[1024];
        String base64Image;
        try {
            while (image.read(bytes) != -1) {
                baos.write(bytes);
            }
            base64Image = Base64.getEncoder().encodeToString(baos.toByteArray());
        }catch (Exception e){
            e.printStackTrace();
            return new Result<>("500",null,null);
        }
        return new Result<>("200",uuid, base64Image);
    }

    @Override
    public Result<Object> checkCaptcha(LoginBody loginBody) {
        if (loginBody.getUuid()==null){
            return new Result<>("500","uuid不存在",loginBody);
        }else if (loginBody.getCode()==null){
            return new Result<>("500","code为空",loginBody);
        }else if (!Boolean.TRUE.equals(redisTemplate.hasKey(loginBody.getUuid()))){
            return new Result<>("500","uuid已过期或不存在",loginBody);
        }else if (!Objects.equals(redisTemplate.opsForValue().get(loginBody.getUuid()), resolveCaptcha(loginBody.getCode()))){
            redisTemplate.delete(loginBody.getUuid());//删除验证码缓存
            return new Result<>("500","验证码不正确",loginBody);
        }else {
            redisTemplate.delete(loginBody.getUuid());//删除验证码缓存，其实这里不删验证码也会过期，没什么风险
            return new Result<>("200","验证码正确",loginBody);
        }
    }

    @Override
    public String resolveCaptcha(String code) {
        // 其他处理逻辑
        return code.toLowerCase();
    }


}
